package com.zh.async.service;

import com.zh.async.AsyncTaskManager;
import com.zh.async.enums.AsyncErrprEnum;
import com.zh.async.exception.AsyncException;
import com.zh.async.utils.AsyncThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.function.Supplier;

/**
 * @desc: 异步任务管理器
 * @Author：zhanghang
 * @Date：2025/8/23 14:32
 */
@Slf4j
@Component
public class DefaultAsyncTaskManager implements AsyncTaskManager {
    @Override
    public <T> T submitTask(Supplier<T> task) {
        log.info("[DefaultAsyncTaskManager] Simple 提交异步任务");
        CompletableFuture<T> future = CompletableFuture.supplyAsync(task, AsyncThreadPoolUtils.getThreadPoolExecutor());
        T t = null;
        try {
            t = future.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new AsyncException(AsyncErrprEnum.INVOKE_ERROR.getCode(), AsyncErrprEnum.INVOKE_ERROR.getMessage());
        }
        return t;
    }
}
